package com.ftg.learn.order.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ftg.learn.order.entity.Order;
import com.ftg.learn.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTask {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Schedules(@Scheduled(cron = "0 * * * * ?"))
    public void cancelOrder() {
        log.info("开始取消超时未支付订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getPayType, 0)
                .le(Order::getOrderTime, time);
        List<Order> list = orderService.list(queryWrapper);
        for (Order order : list) {
            order.setStatus(2);
            orderService.updateById(order);
        }
    }

//    @Scheduled(cron = "0 * * * * ?")
//    public void cancelOrder() {
//        log.info("开始取消超时未支付订单");
//        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
//        //获取order文件下的所有key
//        stringRedisTemplate.keys("order:*").forEach(key -> {
//            String number = key.substring(key.lastIndexOf(":") + 1);
//            String value = stringStringValueOperations.get("order" + number);
//        });
//        log.info("取消订单完成");
//    }

}
